import logEnum from "../enum/log.enum"
const initTime = window.navigationStart || Date.now()
declare global {
  interface Window {
    navigationStart: number
  }
}
export default class Logger {
  timers: Record<string, number> = {}
  handlers = {
    [logEnum.DEBUG]: console.debug,
    [logEnum.INFO]: console.info,
    [logEnum.WARN]: console.warn,
    [logEnum.ERROR]: console.error
  }
  prefix: string
  static level: number = logEnum.INFO
  constructor(name: string) {
    const names = name.split(new RegExp("/|\\\\"))
    this.prefix = "[" + names[names.length - 1].replace("", "") + "]"
  }
  message(e: number) {
    if (Logger.level >= e && console) {
      return (this.handlers[e] ? this.handlers[e] : console.log).bind(console, this.getPrefix())
    }
    return () => {}
  }
  get debug() {
    return this.message(logEnum.DEBUG)
  }
  get debugWarn() {
    return this.message(Logger.level >= logEnum.DEBUG ? logEnum.WARN : logEnum.DEBUG)
  }
  get info() {
    return this.message(logEnum.INFO)
  }
  get warn() {
    return this.message(logEnum.WARN)
  }
  get error() {
    return this.message(logEnum.ERROR)
  }
  time(e: string) {
    Logger.level >= logEnum.DEBUG && (this.timers[e] = Date.now())
  }
  timeEnd(e: string) {
    if (Logger.level >= logEnum.DEBUG) {
      const start = this.timers[e]
      if (!start) return
      const time = (Date.now() - start) / 1000
      this.debug(e, time + "s")
    }
  }
  getPrefix() {
    const time = (Date.now() - initTime) / 1000 + "s"
    return `${this.prefix} ${time}`
  }
}
